package controller;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.dao.registerOrder.DeviceDAOImpl;
import model.dao.registerOrder.SearchClientImpl;
import model.service.Device;
import model.user.Client;
import model.user.Enterprise;


public class SearchController {
	HttpServletRequest req;
	HttpServletResponse res;
	ServletContext servletContext;
	HttpSession session;
	
	public SearchController(HttpServletRequest req, HttpServletResponse res,
			ServletContext servletContext, HttpSession session) throws ServletException, IOException {
		this.req = req;
		this.res = res;
		this.servletContext = servletContext;
		this.session = session;
		
		if (req.getParameter("task") != null && req.getParameter("task").equalsIgnoreCase("client"))
			searchClient();
		if (req.getParameter("task") != null && req.getParameter("task").equalsIgnoreCase("device"))
			searchDevice();
		
		return;

	}
	
	public void searchClient() throws ServletException, IOException {
		
		if (req.getParameter("value") != null) {
			
			SearchClientImpl sc = new SearchClientImpl();
			Client c = sc.getClient(req.getParameter("value"));
			if (c == null) {
				Enterprise e = sc.getEnterprise(req.getParameter("value"));
				req.setAttribute ("name", e.getName());
				req.setAttribute("id", e.getCustomer());
			}
			else {
				//req.setAttribute("name", c.getFirst_name());
				req.setAttribute ("name", c.getFirst_name() + " " + c.getLast_name());
				req.setAttribute("id", c.getCustomer());
			}
		}
		servletContext.getRequestDispatcher("/search_client.jsp").forward(req, res);
		return;
	}
	
	public void searchDevice() throws ServletException, IOException {
		Device device = null;
		if (req.getParameter("value") != null) {
			DeviceDAOImpl dao = new DeviceDAOImpl();
			device = dao.searchDevice(req.getParameter("value"));
			if (device == null) {
				Device d = new Device();
				d.setName(req.getParameter("value"));
				int id = dao.insertDevice(d);
				device = dao.getDeviceById(id);
			}
		}
		req.setAttribute("id", device.getDevice());
		req.setAttribute("name", device.getName());
		servletContext.getRequestDispatcher("/search_device.jsp").forward(req, res);
		return;
	}

}